/*
 * Copyright 2011-2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.service;

import java.io.IOException;
import java.util.concurrent.Semaphore;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;

/**
 * Helper class to safely share IndexSearch instances across multiple threads.
 * Ensures that a searcher is closed only once all threads have finished using
 * it.
 * 
 * <pre>
 * IndexSearcher s = manager.acquire();
 * try {
 * 	// Do searching, doc retrieval, etc. with s
 * } finally {
 * 	manager.release(s);
 * }
 * // Do not use s after this!
 * s = null;
 * </pre>
 * 
 */
public class SearchManager {
	protected volatile IndexSearcher currentSearcher;
	protected final Semaphore acquireLock = new Semaphore(1);
	private final Log _logger = LogFactory.getLog(SearchManager.class);

	public SearchManager(IndexReader indexReader) throws IOException {
		currentSearcher = new IndexSearcher(indexReader);
	}

	/**
	 * Reopen index if it has changed (writer.commit() adding/deleting
	 * document). Note this does not close existing IndexSearchers or underlying
	 * readers which continue to exist until released.
	 * 
	 * @return IndexSearcher
	 */
	public IndexSearcher aquire() {
		try {
			IndexReader indexReader = currentSearcher.getIndexReader();
			_logger.info("reader ref count " + indexReader.getRefCount());
			if (indexReader.isCurrent() == false) {
				if (acquireLock.tryAcquire()) {
					// create a new "cold" reader and update the currentSearcher
					// based on this reader.
					indexReader = currentSearcher.getIndexReader()
							.reopen();
					release(currentSearcher);
					currentSearcher = new IndexSearcher(indexReader);
				}
			}
			indexReader.incRef();
		} catch (Exception e) {
			_logger.error(e.getMessage());
		} finally {
			acquireLock.release();
		}
		return currentSearcher;
	}

	/**
	 * Release the searcher previously obtained with acquire (in reality we
	 * release (close if refcount == 0) the underlying reader).
	 */
	public synchronized void release(IndexSearcher searcher) throws IOException {
		assert searcher != null;
		searcher.getIndexReader().decRef();
		// do we close the searcher?
		_logger.info("release reader ref count "
				+ searcher.getIndexReader().getRefCount());
		if (searcher.getIndexReader().getRefCount() == 0) {
			searcher.close();
		}
	}
	
	public void close() throws IOException {
		release(currentSearcher);
	}
}
